import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:toolbox/manager/hive/hiveHelper.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:http/http.dart' as http;
import 'package:html/parser.dart' as html;

import '../common/styles.dart';
import '../models/FetchWebsiteInfoModel.dart';

launchURL(String url) async {
  final Uri uri = Uri.parse(url);
  if (!await launchUrl(uri, mode: LaunchMode.externalApplication)) {
    throw Exception('Could not launch $uri');
  }
}

showToast(String msg, {Color? color, ToastGravity? gravity, Toast toastLength = Toast.LENGTH_SHORT}) {
  Fluttertoast.showToast(
    msg: msg,
    toastLength: toastLength,
    // 持续显示时间，Toast.LENGTH_SHORT表示短时间，Toast.LENGTH_LONG表示长时间
    gravity: gravity ?? ToastGravity.CENTER,
    // 显示位置，可以是顶部、中间或底部
    backgroundColor: color ?? Styles.mainToastColor,
    // 背景颜色
    textColor: Colors.white,
    // 文本颜色
    fontSize: 16.0, // 文本大小
  );
}

void copyText(String text) {
  Clipboard.setData(ClipboardData(text: text)).then((value) {
    showToast('已复制到粘贴板');
  });
}

bool areHostnamesEqual(String url1, String url2) {
  String? getHostname(String url) {
    return url;
    RegExp regExp = RegExp(r'^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:/\n?]+)');
    RegExpMatch? match = regExp.firstMatch(url);
    return match?.group(1);
  }

  String? hostname1 = getHostname(url1);
  String? hostname2 = getHostname(url2);

  return (hostname1 != null && hostname2 != null && hostname1 == hostname2);
}

String? hasStarUrl(String url) {
  var list = HiveHelper.instance.getAllStarWebUrl();
  for(var model in list){
    if (areHostnamesEqual(model.url, url)) {
      return model.url;
    }
  }
  return null;
}

/// 当[fromCatch] 为 false时，根据url清除原来的内容，重新捕获；
Future<FetchWebsiteInfoModel?> fetchWebsiteInfo(String url, {bool fromCatch = true}) async {
  FetchWebsiteInfoModel? model = HiveHelper.instance.findWebsiteInfoFetchByUrl(url);
  if (fromCatch && model != null) {
    return model;
  }
  try {
    // 发送 HTTP 请求
    final response = await http.get(Uri.parse(url));
    if (response.statusCode != 200) {
      throw Exception('Failed to load page: ${response.statusCode}');
    }

    // 解析最终 URL（处理重定向）
    final finalUri = response.request?.url ?? Uri.parse(url);

    // 解析 HTML 文档
    final document = html.parse(response.body);

    // 获取标题
    final title = document.querySelector('title')?.text ?? url;

    // 处理 base 标签
    final baseElement = document.querySelector('base');
    String? baseHref = baseElement?.attributes['href'];
    Uri baseUri = finalUri;
    if (baseHref != null) {
      baseUri = finalUri.resolve(baseHref);
    }

    // 查找可能的图标链接
    String? iconUrl;
    final links = document.querySelectorAll('link');
    for (var link in links) {
      final rel = link.attributes['rel'];
      if (rel == null) continue;

      final relTypes = rel.split(' ');
      if (relTypes.contains('icon') ||
          relTypes.contains('shortcut icon') ||
          relTypes.contains('apple-touch-icon')) {
        final href = link.attributes['href'];
        if (href != null) {
          iconUrl = baseUri.resolve(href).toString();
          break; // 简单起见，取第一个符合条件的
        }
      }
    }

    // 如果未找到，尝试默认的 favicon.ico
    iconUrl ??= finalUri.resolve('/favicon.ico').toString();

    model = FetchWebsiteInfoModel(title, iconUrl, url, finalUri.toString());
    // 清除缓存
    if (!fromCatch) {
      HiveHelper.instance.deleteFetchWebsiteInfo(url);
    }
    HiveHelper.instance.addFetchWebsiteInfo(model);
    return model;
  } catch (e) {
    return null;
  }
}